import { login, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, setCookie, removeCookie } from '@/utils/auth'
import { defineStore } from "pinia"
import defAva from '@/assets/images/user/avatar-bg.png'
export const useUserStore = defineStore({
  id: 'user', // 必填且唯一
  state: () => {
    return {
      name: '张三',
      token: getToken(),
      avatar: '',
      roles: [] as Array<string>,
      permissions: []
    }
  },
  getters: {
    userName: (state) => {
      return state.name
    }
  },
  actions: {
    updateName(name: string) {
      this.name = name
    },
    // 登录
    Login(userInfo: { username: string; password: any; code: any; uuid: any }) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise<void>((resolve, reject) => {
        login(username, password, code, uuid).then((res) => {
          setToken(res.token)
          setCookie('u', username, { path: '/' })
          resolve()
        }).catch((error: any) => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        getInfo().then((res: any) => {
          const user = res.user
          const avatar = user.avatar == "" ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            this.roles = res.roles
            this.permissions = res.permissions
          } else {
            this.roles = ['ROLE_DEFAULT']
          }
          this.name = user.userName
          this.avatar = avatar
          resolve(res)
        }).catch((error: any) => {
          reject(error)
        })
      })
    },
    // 退出登录
    LogOut() {
      return new Promise<void>((resolve) => {
        removeToken()
        removeCookie('u', { path: '/' })
        resolve()
      })
    }
  }
})